﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization;

namespace Odelle.Utils
{
    public class SerializableDictionary<Tkey, Tvalue> : Dictionary<Tkey, Tvalue>, IXmlSerializable
    {
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;    //schema is not implemented
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Word));
            reader.Read();
            while (reader.NodeType!= XmlNodeType.None && reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                Word word = serializer.Deserialize(reader) as Word;
                if (word != null) Add(word.Key, word.Value);
            }
            reader.Read();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Word));
            foreach (var key in Keys)
            {
                serializer.Serialize(writer, new Word(key, this[key]));
            }
        }

        public class Word
        {
            public Word() { }
            public Word(Tkey key, Tvalue value) { Key = key; Value = value; }

            [XmlAttribute()]
            public Tkey Key { get; set; }
            public Tvalue Value { get; set; }
        }
    }
}
